<template>
  <BasicModal
    v-bind="$attrs"
    width="700px"
    @register="registerModal"
    title="添加下级"
    @ok="handleAddUser"
  >
    <a-form
      ref="formRef"
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 20 }"
      autocomplete="off"
    >
      <a-form-item
        label="代理昵称"
        name="nickname"
        :rules="[{ required: true, message: '请输入代理昵称' }]"
      >
        <a-row :gutter="8">
          <a-col span="20">
            <a-input v-model:value="formState.nickname" />
          </a-col>
          <a-col>
            <img
              @click="getRandomNick"
              src="../../../assets/icons/touzi.png"
              alt="touzi"
              width="30"
              style="cursor: pointer"
            />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item
        label="代理账号"
        name="username"
        :rules="[{ required: true, message: '请输入代理账号' }]"
      >
        <a-row :gutter="8">
          <a-col span="20">
            <a-input v-model:value="formState.username" />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item
        label="登录密码"
        name="password"
        :rules="[{ required: true, message: '请输入密码' }]"
      >
        <a-row :gutter="8">
          <a-col span="20">
            <a-input-password v-model:value="formState.password" />
          </a-col>
          <a-col>
            <img
              @click="getRandomPwd"
              src="../../../assets/icons/touzi.png"
              alt="touzi"
              width="30"
              style="cursor: pointer"
            />
          </a-col>
        </a-row>
      </a-form-item>

      <a-form-item label="联系方式" name="contact">
        <a-row :gutter="8">
          <a-col :span="20"><a-input v-model:value="formState.contact" /></a-col>
        </a-row>
      </a-form-item>
    </a-form>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { AddAgentApi, GetRandomApi } from '@/api/group';
  import { ref } from 'vue';
  import message from '@/views/form-design/utils/message';

  let reloadFunc;
  const [registerModal, { closeModal }] = useModalInner((reload) => {
    reloadFunc = reload;
  });
  const formRef = ref();
  const formState = ref({
    nickname: '',
    username: '',
    password: '',
    contact: '',
  });

  const getRandomNick = () => {
    GetRandomApi(0).then((res) => {
      console.log(res);
      formState.value.nickname = res.result;
    });
  };

  const getRandomPwd = () => {
    GetRandomApi(1).then((res) => {
      formState.value.password = res.result;
    });
  };

  const handleAddUser = () => {
    formRef.value.validate().then((params) => {
      AddAgentApi(params).then(() => {
        message.success('添加成功');
        reloadFunc();
        closeModal();
      });
    });
  };
</script>
